package middleware

import (
	"fmt"
	"gin/util"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
	"net/http"
	"strconv"
	"time"
)

func SignMiddleware() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		//获取header
		appid := ctx.GetHeader("appid")
		timestamp := ctx.GetHeader("timestamp")
		sign := ctx.GetHeader("sign")
		if appid == "" || timestamp == "" || sign == "" {
			ctx.JSON(http.StatusUnauthorized, gin.H{"code": 405, "msg": "缺少签名参数"})
			ctx.Abort()
			return
		}
		//字符串转int64
		parseInt, err := strconv.ParseInt(timestamp, 10, 64)
		if err != nil {
			ctx.JSON(http.StatusUnauthorized, gin.H{"code": 405, "msg": "时间戳有误"})
			ctx.Abort()
			return
		}
		if time.Now().Unix()*1000-parseInt > 30000 {
			//ctx.JSON(http.StatusUnauthorized, gin.H{"code": 405, "msg": "签名失效"})
			//ctx.Abort()
			//	return
		}
		key := viper.GetString("sign.signKey")

		md5Str := util.MD5(appid + timestamp + key)
		fmt.Println("签名：", md5Str)
		//用户是否存在
		if md5Str != sign {
			ctx.JSON(http.StatusUnauthorized, gin.H{"code": 405, "msg": "签名失败"})
			ctx.Abort()
			return
		}
		ctx.Next()

	}
}
